//#define __DEBUG__
// by Xeno
#define THIS_FILE "fn_updatelb.sqf"
#include "x_setup.sqf"

KEGs_updating_lb = true;
private ["_cLBTargets", "_sidecache", "_namecache", "_deadstr", "_clbcols", "_idx", "_oside", "_rr", "_name", "_i", "_colidx", "_prest"];
_cLBTargets = _this select 0;
_sidecache = _this select 1;
_namecache = _this select 2;
_deadstr = _this select 3;
_clbcols = _this select 4;
_uns = []; _rest = []; _idx = 0; _prest = [];
{
	_oside = _sidecache select _idx;
	if (_oside in KEGs_ShownSides) then {
		_rr = _x call KEGs_fnc_CheckU; 
		if (_rr select 0) then {
			_uns set [count _uns, _x];
			_name = _namecache select _idx;
			if !(_rr select 1) then {_name = _deadstr + _name};
			_colidx =  if (_idx == KEGs_tgtIdx) then {0} else {if (_rr select 1) then {switch (_oside) do {case blufor: {1};case opfor: {2};case independent: {3};case civilian: {4};}} else {5}};
			if (isNil "KEGs_withSpect") then {
				_rest set [count _rest, [_name, _idx, _colidx]];
			} else {
				if (_x != player) then {
					_rest set [count _rest, [_name, _idx, _colidx]];
				} else {
					_prest = [_name, _idx, _colidx];
				};
			};
		};
	};
	_idx = _idx + 1;
	if (KEGs_exitspect) exitWith {};
} forEach KEGs_deathCam;
if (KEGs_exitspect) exitWith {};
if (count _prest > 0) then {
	_rest resize (count _rest + 1);
	for "_v" from (count _rest - 1) to 1 step - 1 do {
		_rest set [_v, _rest select (_v - 1)];
	};
	_rest set [0, _prest];
	_uns = _uns - [player];
	_uns resize (count _uns + 1);
	for "_v" from (count _uns - 1) to 1 step - 1 do {
		_uns set [_v, _uns select (_v - 1)];
	};
	_uns set [0, player];
};
KEGs_units = _uns;
lbClear _cLBTargets;
{
	_i = lbAdd [_cLBTargets, _x select 0];
	lbSetValue [_cLBTargets, _i, _x select 1];
	lbSetColor [_cLBTargets, _i, _clbcols select (_x select 2)];
	if (!isNil "d_a_d_cur_unit_name" && {d_a_d_cur_unit_name == _x select 0}) then {
		lbSetCurSel [_cLBTargets, _i];
		d_a_d_cur_unit_name = nil;
	};
	if (KEGs_exitspect) exitWith {};
} forEach _rest;
KEGs_lastAutoUpdateLB = time;
KEGs_NeedUpdateLB = false;
sleep 1;
KEGs_updating_lb = false;